package com.atguigu.juc;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author tongatong
 * @name ReadWriteLockDemo
 * @description 读写锁，用于读多，写少的场合。
 * 案例：
 *   3读，5写。
 *
 * 读 读 共享
 * 读 写 共享
 * 写 写 不共享
 *
 * @date 2021/9/4
 * @time 0:16
 */
public class ReadWriteLockDemo {
    public static void main(String[] args) {
        MyCache myCache = new MyCache();

        for (int i = 1; i <= 3; i++) {
            int finalI = i;
            new Thread(() -> {
                myCache.write(Thread.currentThread().getName(), finalI);

            }, String.valueOf(i)).start();
        }

        try {
            TimeUnit.MILLISECONDS.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        for (int i = 1; i <= 5; i++) {
            new Thread(() -> {
                myCache.read(Thread.currentThread().getName());

            }, String.valueOf(i)).start();
        }
    }
}

class MyCache{
    private static Map<String, Integer> map = new HashMap<>();
    ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    Lock writeLock = readWriteLock.writeLock();
    Lock readLock = readWriteLock.readLock();

    public void write(String key, Integer value) {
        writeLock.lock();
        try {
            System.out.println("写入线程"+Thread.currentThread().getName()+"\t"+"---写入");
            Integer result = map.put(key, value);
            System.out.println("写入线程"+Thread.currentThread().getName()+"\t"+"---写入完成"+result);
        } finally {
            writeLock.unlock();
        }
    }
    public void read(String key) {
        readLock.lock();
        try {
            System.out.println("读入线程"+Thread.currentThread().getName()+"\t"+"---准备读入");
            Integer value = map.get(key);
            System.out.println("读入线程"+Thread.currentThread().getName()+"\t"+"---读入完成"+value);
        } finally {
            readLock.unlock();
        }
    }

}